package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeline(Long userId, ObjectId movementId) {

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> list = mongoTemplate.find(query, Friend.class);   //大V，有100w好友
        //3、记录好友和动态的关系
        for (Friend friend : list) { //循环，保存  1条用1毫秒 ，100秒
            MovementTimeLine timeLine = new MovementTimeLine();
            timeLine.setMovementId(movementId); //动态id
            timeLine.setUserId(userId); //发布人id
            timeLine.setFriendId(friend.getFriendId()); //当前发布人的好友id
            timeLine.setCreated(System.currentTimeMillis()); //创建时间
            mongoTemplate.save(timeLine);
        }
    }
}
